#include "Video.h"
#include "version.h"

#include <string>
#include <SDL.h>
#include <gl.h>
#include <glu.h>

namespace Lame3d
{
	// VideoConfig
	void VideoConfig::Load(ConfigFile &c)
	{
		ConfigFile::Entry *e;
		
		e = c.Find("width");
		if(e != NULL) {
			Width = e->Int();
		} else {
			Width = 800;
		}
		
		e = c.Find("height");
		if(e != NULL) {
			Height = e->Int();
		} else {
			Height = 600;
		}
		
		e = c.Find("depth");
		if(e != NULL) {
			Depth = e->Int();
		} else {
			Depth = 0;
		}
		
		e = c.Find("fullscreen");
		if(e != NULL) {
			Fullscreen = (e->Int() == 1);
		} else {
			Fullscreen = false;
		}
	}
	
	void VideoConfig::Save(ConfigFile &c)
	{
		c["width"] = Width;
		c["height"] = Height;
		c["depth"] = Depth;
		c["fullscreen"] = Fullscreen ? 1 : 0;
	}
	
	// DisplayManager
	DisplayManager::DisplayManager(const char* configPath)
			: config(configPath)
	{
		currentConfig.Load(config);
		workingConfig = currentConfig;
		ratio = float(currentConfig.Width)/float(currentConfig.Height);
		
		startDisplay();
	}
	
	DisplayManager::~DisplayManager()
	{
		workingConfig.Save(config);
	}
	
	const VideoConfig& DisplayManager::CurrentConfig() const
	{
		return currentConfig;
	}
	
	VideoConfig& DisplayManager::WorkingConfig()
	{
		return workingConfig;
	}
	
	float DisplayManager::Ratio() const
	{
		return ratio;
	}
	
	void DisplayManager::startDisplay()
	{
		if(SDL_Init(SDL_INIT_VIDEO) == -1) {
			throw "Error intializing SDL video subsystem.";
		}
		if(SDL_SetVideoMode(
				currentConfig.Width,
				currentConfig.Height,
				currentConfig.Depth,
				SDL_HWSURFACE | SDL_OPENGL | (currentConfig.Fullscreen ? SDL_FULLSCREEN : 0))
				== NULL) {
			throw "Error creating SDL display surface.";
		}
		std::string wmCaption("Lame3d Engine: Verison: ");
		wmCaption += VERSION;
		SDL_WM_SetCaption(wmCaption.c_str(), NULL); 
		
		// Setup GL stuff
		glEnable(GL_ALPHA_TEST);
		glEnable(GL_CULL_FACE);
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_TEXTURE_2D);
		// Texture blending for transparent textures (incl. mouse)
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		// Texture weirdness correction (caused by SDL loader)
		glMatrixMode(GL_TEXTURE);
		glOrtho(0, 2, 2, 0, 1, 0);
		glMatrixMode(GL_MODELVIEW);
		// Transparent colors (?)
		glEnable(GL_COLOR_MATERIAL);
	}
}
